<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Providers;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use OpenTracing\GlobalTracer;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register()
    {
    }

    /**
     * Bootstrap any application services.
     */
    public function boot()
    {
        if (config('app.env') === 'testing') {
            $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations/test');
        }

        if (config('app.env') === 'test') {
            DB::listen(function ($query) {
                $tracer = GlobalTracer::get();
                $activeSpan = $tracer->getActiveSpan();
                $endTime = microtime(true);
                $span = $tracer->startSpan('db.query', [
                    'start_time' => (int)(($endTime - $query->time / 1000) * 1000 * 1000),
                    'child_of' => $activeSpan->getContext(),
                ]);
                $sql = $query->sql;
                if (! Arr::isAssoc($query->bindings)) {
                    foreach ($query->bindings as $key => $value) {
                        $sql = Str::replaceFirst('?', "'{$value}'", $sql);
                    }
                }
                $span->setTag('db.sql', $sql);
                $span->setTag('db.query_time', $query->time);
                $span->finish();
            });
        }
    }
}
